package com.ehotting.edsta.simulation.controller;

import com.alibaba.fastjson.JSON;
import com.ehotting.eaf.core.domain.R;
import com.ehotting.eaf.core.web.controller.BaseController;
import com.ehotting.eaf.security.service.TokenService;
import com.ehotting.mqbd.api.bean.MqApplicationContext;
import com.ehotting.mqbd.api.enums.SendTypeEnum;
import com.ehotting.mqbd.api.enums.SolveStepEnum;
import com.ehotting.mqbd.api.enums.TopicEnum;
import com.ehotting.mqbd.core.service.MQService;
import com.ehotting.mqbd.core.manager.AgentLinkManager;
import com.ehotting.mqbd.zw.api.bean.ZwMQTcpData;
import com.ehotting.mqbd.zw.api.constants.ActionConstants;
import com.ehotting.mqbd.zw.api.domain.netty.ZwCommPacket;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@Api(tags = "ZwController", description = "中望多物理场仿真求解器服务接口")
@RestController
@RequestMapping("/zw")
public class SimulationController extends BaseController {

    @Resource(name="mqService")
    private MQService mqService;

    @Autowired
    private MqApplicationContext mqApplicationContext;
    @Autowired
    private AgentLinkManager agentLinkManager;

    @Autowired
    private TokenService tokenService;

    @PostMapping("/sendPkg")
    public R<ZwCommPacket> sendZwPkg(@RequestBody ZwCommPacket zwCommPacket) {
        logger.info("Start sendZwPkg");
        Long userId = tokenService.getLoginUser().getUserid();
        logger.info("userId:{}",userId);
        String agentId = agentLinkManager.genAgentId(mqApplicationContext.getModule(),userId,"0");
        ZwMQTcpData data = ZwMQTcpData.create(TopicEnum.CONCURRENCY,mqApplicationContext,
                agentId,
                "");

        data.setSolveStep(SolveStepEnum.MULTI);

        if(zwCommPacket.getHead().getCmd() == ActionConstants.Cmd_JobCommit.getZwCommandVal()){
            data.setTopic(TopicEnum.BLOCK);
        }

        data.setRequest(zwCommPacket);

        data.setSendType(new SendTypeEnum[]{SendTypeEnum.REDIS_REQUEST_BODY});

        ZwMQTcpData response = (ZwMQTcpData)mqService.request(data,120);
        if(response==null){
            logger.error("response is null,requestBody:{}",JSON.toJSONString(data));
        }
        logger.info("JSON.toJSONString(response):{}", JSON.toJSONString(response));
        logger.info("Finish sendZwPkg");
        return response!=null?R.ok(response.getResponse()):R.okMsg("发送失败");

    }
}
